-- 基于tradeTntercept.lua的交易拦截器
-- 专门监听当前游戏的TradeEvents事件

local HttpService = game:GetService("HttpService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")

local LocalPlayer = Players.LocalPlayer

-- 日志函数
local function log(s)
    local success, err = pcall(function()
        appendfile("log.txt", string.format("[%s] %s\n", os.date("%Y-%m-%d %H:%M:%S"), tostring(s)))
    end)
    if not success then
        writefile("log.txt", string.format("[%s] %s\n", os.date("%Y-%m-%d %H:%M:%S"), tostring(s)))
    end
end

-- 暂时禁用所有可能导致GetFarmAncestor错误的监听器
log("⚠️ 已暂时禁用所有事件监听器，避免GetFarmAncestor错误")
log("🔍 [交易拦截器] 仅使用RemoteEvent调用拦截功能...")


-- 安全获取游戏服务，避免触发GetFarmAncestor错误
local function safeGetGameEvents()
    local success, result = pcall(function()
        return ReplicatedStorage:FindFirstChild("GameEvents")
    end)
    if not success then
        log("❌ 无法安全访问GameEvents文件夹: " .. tostring(result))
        return nil
    end
    return result
end

local gameEvents = safeGetGameEvents()
if not gameEvents then
    log("❌ 找不到GameEvents文件夹")
    return
end

local function safeGetTradeEvents()
    local success, result = pcall(function()
        return gameEvents:FindFirstChild("TradeEvents")
    end)
    if not success then
        log("❌ 无法安全访问TradeEvents文件夹: " .. tostring(result))
        return nil
    end
    return result
end

local tradeEvents = safeGetTradeEvents()
if not tradeEvents then
    log("❌ 找不到TradeEvents文件夹")
    return
end

log("🔍 [交易拦截器] 开始监听TradeEvents事件...")

-- 安全监听所有TradeEvents中的事件
local function safeSetupTradeListeners()
    local success, result = pcall(function()
        for _, event in ipairs(tradeEvents:GetChildren()) do
            if event and event:IsA("RemoteEvent") then
                log("📡 监听TradeEvents事件: " .. event.Name)
                
                pcall(function()
                    event.OnClientEvent:Connect(function(...)
                        local args = {...}
                        print("【🟡 " .. event.Name .. " 事件捕获】")
                        print("参数数量:", #args)
                        
                        for i, arg in ipairs(args) do
                            if typeof(arg) == "table" then
                                local success, json = pcall(function()
                                    return HttpService:JSONEncode(arg)
                                end)
                                if success then
                                    log("TradeEvents/" .. event.Name .. " 参数[" .. i .. "] 类型: " .. typeof(arg) .. " 值: " .. json)
                                else
                                    log("TradeEvents/" .. event.Name .. " 参数[" .. i .. "] 类型: " .. typeof(arg) .. " 值: [无法序列化]")
                                end
                            else
                                log("TradeEvents/" .. event.Name .. " 参数[" .. i .. "] 类型: " .. typeof(arg) .. " 值: " .. tostring(arg))
                            end
                        end
                    end)
                end)
            end
        end
    end)
    if not success then
        log("❌ 设置TradeEvents监听器时出错: " .. tostring(result))
    end
end

safeSetupTradeListeners()
-- 简化的RemoteEvent调用拦截器，避免GetFarmAncestor错误
local function safeSetupInterceptor()
    local success, mt = pcall(function()
        return getrawmetatable(game)
    end)

    if success and mt then
        local setReadonlySuccess = pcall(function()
            setreadonly(mt, false)
        end)
        
        if not setReadonlySuccess then
            log("❌ 无法设置metatable为可写")
            return false
        end
        
        local oldNamecall = mt.__namecall

        -- 专门针对Grow-a-Garden游戏的事件列表
        local target_list = {
            -- 交易相关事件
            ["SendRequest"] = true,
            ["RespondRequest"] = true,
            ["Accept"] = true,
            ["Decline"] = true,
            ["AddItem"] = true,
            ["RemoveItem"] = true,
            ["Confirm"] = true,
            ["UpdateTradeState"] = true,
            ["SetSheckles"] = true,
            
            -- 礼物相关事件
            ["SendGiftTo"] = true,
            ["GiftPrompted"] = true,
            ["FriendGiftEvent"] = true,
            ["GiftPet"] = true,
            ["AcceptPetGift"] = true,
            ["PetGiftingService"] = true,
            
            -- 植物/果实相关事件
            ["Plant"] = true,
            ["Harvest"] = true,
            ["Seed"] = true,
            ["Fruit"] = true,
            ["Grow"] = true,
            ["Water"] = true,
            
            -- 通用交易事件
            ["Trade"] = true,
            ["Exchange"] = true,
            ["Transfer"] = true
        }

        mt.__namecall = function(self, ...)
            local method = getnamecallmethod()
            local args = {...}
            local remoteName = tostring(self)

            -- 优化错误屏蔽逻辑
            if remoteName:match("Farm") or remoteName:match("GameAnalyticsError") then
                -- 直接返回，不执行原始调用，避免错误传播
                return
            end

            -- 记录所有RemoteEvent调用
            if (method == "FireServer" or method == "InvokeServer") then
                -- 记录所有RemoteEvent调用
                log("🔍 RemoteEvent调用: " .. remoteName .. ":" .. method .. " 参数数量: " .. #args)
                
                -- 详细记录所有参数
                for i, arg in ipairs(args) do
                    if typeof(arg) == "table" then
                        local success, json = pcall(function()
                            return HttpService:JSONEncode(arg)
                        end)
                        if success then
                            log("  参数[" .. i .. "] 类型: " .. typeof(arg) .. " 值: " .. json)
                        else
                            log("  参数[" .. i .. "] 类型: " .. typeof(arg) .. " 值: [无法序列化]")
                        end
                    else
                        log("  参数[" .. i .. "] 类型: " .. typeof(arg) .. " 值: " .. tostring(arg))
                    end
                end
                
                -- 检查是否是交易相关的调用
                local isTradeRelated = target_list[remoteName] or 
                                      remoteName:match("Trade") or 
                                      remoteName:match("Gift") or 
                                      remoteName:match("Request") or
                                      remoteName:match("Accept") or
                                      remoteName:match("Decline") or
                                      remoteName:match("Confirm") or
                                      remoteName:match("Item") or
                                      remoteName:match("Pet") or
                                      remoteName:match("Plant") or
                                      remoteName:match("Harvest") or
                                      remoteName:match("Seed") or
                                      remoteName:match("Fruit") or
                                      remoteName:match("Grow") or
                                      remoteName:match("Water") or
                                      remoteName:match("Exchange") or
                                      remoteName:match("Transfer") or
                                      remoteName:match("Coins") or
                                      remoteName:match("Money")
                
                if isTradeRelated then
                    print("【🔴 交易调用拦截】")
                    print("事件:", remoteName)
                    print("方法:", method)
                    
                    log("🎯 交易调用 ==> " .. remoteName .. ":" .. method)
                    
                    -- 特别标记交易相关调用
                    for i, arg in ipairs(args) do
                        if typeof(arg) == "table" then
                            local success, json = pcall(function()
                                return HttpService:JSONEncode(arg)
                            end)
                            if success then
                                log("  🎯 交易参数[" .. i .. "] 类型: " .. typeof(arg) .. " 值: " .. json)
                            else
                                log("  🎯 交易参数[" .. i .. "] 类型: " .. typeof(arg) .. " 值: [无法序列化]")
                            end
                        else
                            log("  🎯 交易参数[" .. i .. "] 类型: " .. typeof(arg) .. " 值: " .. tostring(arg))
                        end
                    end
                end
            end
            
            -- 安全执行原始调用
            local success, results = pcall(function()
                return {oldNamecall(self, unpack(args))}
            end)
            
            if success then
                return unpack(results)
            else
                -- 如果出错，记录错误但不传播
                log("⚠️ 屏蔽错误调用: " .. remoteName .. ":" .. method)
                if method == "InvokeServer" then
                    return nil
                else
                    return
                end
            end
        end
        
        log("✅ 成功设置调用拦截器")
        return true
    else
        log("❌ 无法设置调用拦截器")
        return false
    end
end


safeSetupInterceptor()

-- 创建监控UI
local function createMonitorUI()
    local screenGui = Instance.new("ScreenGui")
    screenGui.Name = "TradeMonitorUI"
    screenGui.ResetOnSpawn = false
    screenGui.Parent = LocalPlayer:WaitForChild("PlayerGui")
    
    local mainFrame = Instance.new("Frame")
    mainFrame.Name = "MainFrame"
    mainFrame.Size = UDim2.new(0, 300, 0, 200)
    mainFrame.Position = UDim2.new(0, 10, 0, 10)
    mainFrame.BackgroundColor3 = Color3.fromRGB(40, 40, 40)
    mainFrame.BorderSizePixel = 0
    mainFrame.Parent = screenGui
    
    local titleLabel = Instance.new("TextLabel")
    titleLabel.Name = "Title"
    titleLabel.Size = UDim2.new(1, 0, 0, 30)
    titleLabel.Text = "交易拦截器"
    titleLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
    titleLabel.TextScaled = true
    titleLabel.Font = Enum.Font.SourceSansBold
    titleLabel.BackgroundTransparency = 1
    titleLabel.Parent = mainFrame
    
    local statusLabel = Instance.new("TextLabel")
    statusLabel.Name = "Status"
    statusLabel.Size = UDim2.new(1, -20, 0, 120)
    statusLabel.Position = UDim2.new(0, 10, 0, 40)
    statusLabel.Text = "状态: 监听中...\n正在拦截所有交易事件\n请执行交易操作\n查看控制台输出"
    statusLabel.TextColor3 = Color3.fromRGB(200, 200, 200)
    statusLabel.TextScaled = true
    statusLabel.Font = Enum.Font.SourceSans
    statusLabel.BackgroundTransparency = 1
    statusLabel.Parent = mainFrame
    
    local closeButton = Instance.new("TextButton")
    closeButton.Name = "CloseButton"
    closeButton.Size = UDim2.new(0, 30, 0, 30)
    closeButton.Position = UDim2.new(1, -40, 0, 10)
    closeButton.Text = "X"
    closeButton.TextColor3 = Color3.fromRGB(255, 255, 255)
    closeButton.TextScaled = true
    closeButton.Font = Enum.Font.SourceSansBold
    closeButton.BackgroundColor3 = Color3.fromRGB(80, 80, 80)
    closeButton.BorderSizePixel = 0
    closeButton.Parent = mainFrame
    
    closeButton.MouseButton1Click:Connect(function()
        screenGui:Destroy()
    end)
    
    return screenGui
end

-- 创建监控UI
createMonitorUI()

log("✅ [交易拦截器] 启动成功，请执行一次交易流程来抓包")
log("📡 正在监听以下事件:")
log("  - 拦截所有RemoteEvent调用")
log("⚠️  已暂时禁用所有事件监听器，避免GetFarmAncestor错误")
log("🔍 仅使用RemoteEvent调用拦截功能进行交易分析")

print("🔍 [交易拦截器] 已启动，请执行交易操作...")
print("📡 正在监听RemoteEvent调用...")
print("⚠️  已暂时禁用所有事件监听器，避免GetFarmAncestor错误")
print("📝 所有RemoteEvent调用都会记录到log.txt文件中")
print("🎯 请执行一次完整的交易流程来抓包分析")
